<script setup>
import {onBeforeMount, ref} from "vue";
import VIcon from "@/components/icon/VIcon.vue";
import {useRouter} from "vue-router";
import {deleteArticle, getArticleList} from "@/api/article.js";
import {ElMessage} from "element-plus";
import {getCategoryDropList} from "@/api/category.js";

const $router = useRouter();

const queryForm = ref({
  title: '',
  status: [0, 1],
  categoryId: undefined,
});

const statusList = ref([
  {label: '草稿', value: 0},
  {label: '已发布', value: 1},
  {label: '已删除', value: 2},
]);
const categoryList = ref([]);


const articleList = ref([]);
const pagination = ref({
  pageSize: 5,
  pageNum: 1
});
const totalArticleCount = ref(0);
const loading = ref(false);

onBeforeMount(async () => {
  await categoryDropList();
  await doQuery();
});
// 获取文章分类下拉列表
const categoryDropList = async () => {
  await getCategoryDropList().then(res => {
    categoryList.value = res.data;
  }).catch(err => {
    console.log(err);
  });
};

const doQuery = async () => {
  loading.value = true;
  const request = {
    title: queryForm.value.title,
    categoryId: queryForm.value.categoryId,
    statusList: queryForm.value.status?.join(','),
    ...pagination.value
  }
  await getArticleList(request).then(res => {
    console.log(res);
    articleList.value = res.data?.record;
    totalArticleCount.value = res.data?.total;
    const timer = setTimeout(() => {
      loading.value = false;
      clearTimeout(timer);
    }, 500);
  }).catch((err) => {
    console.log(err);
    loading.value = false;
  });
};

const reset = () => {
  queryForm.value = {
    title: '',
    status: [0, 1],
    categoryId: undefined,
  };
};

const writeArticle = () => {
  $router.push({path: '/admin/article/write'});
};
const removeArticle = async (item) => {
  await deleteArticle(item.id).then(res => {
    console.log(res);
    ElMessage.success('删除成功');
    doQuery();
  }).catch(err => {
    console.log(err);
    ElMessage.error('删除失败');
  });
};

const handleCurrentChange = (val) => {
  pagination.value.pageNum = val;
  doQuery();
};
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  doQuery();
};
const doWriteArticle = (item) => {
  $router.push({path: '/admin/article/write', query: {id: item.id}});
};
</script>

<template>
  <div class="v-article-container">
    <div class="v-article-query">
      <h4>查询条件</h4>
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="文章标题">
          <el-input v-model="queryForm.title" placeholder="请输入标题内容" clearable/>
        </el-form-item>
        <el-form-item label="文章分类">
          <el-select v-model="queryForm.categoryId" placeholder="请选择" clearable>
            <el-option v-for="item in categoryList" :key="item.id" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择" clearable multiple>
            <el-option v-for="item in statusList" :key="item.value" :value="item.value" :label="item.label"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doQuery">查询</el-button>
          <el-button type="info" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="v-article-toolbar">
      <el-tooltip effect="dark" content="发布文章" placement="top">
        <v-icon icon="CirclePlus" size="24" @click="writeArticle"/>
      </el-tooltip>
      <span class="v-article-total">文章数量：{{ totalArticleCount }}篇</span>
    </div>
    <div class="v-article-list" v-loading="loading">
      <div class="v-article-item" v-for="item in articleList" :key="item.id"
           :class="item['status'] === 0 ? 'v-draft-status' : (item['status'] === 1 ? 'v-published-status' : (item['status'] === 2 ? 'v-deleted-status' : ''))">
        <div class="v-article-cover">
          <el-image :src="item['coverImage']" fit>
            <template #error>
              <div class="v-image-slot">
                <v-icon icon="Picture" size="80"/>
              </div>
            </template>
          </el-image>
        </div>
        <div class="v-article-main">
          <div class="v-article-title">{{ item.title }}</div>
          <span>{{ item.brief }}</span>
          <div class="v-article-other-info">
            <span>
              <v-icon icon="AlarmClock"/>
              发布时间：{{ item.publishedTime || '-' }}
            </span>
            <span>
              <v-icon icon="CollectionTag"/>
              分类：<span>{{ item.categoryName || '-' }}</span>
            </span>
            <span>
              <v-icon icon="View"/>
              浏览：{{ item.views }}
            </span>
            <span>
              <v-icon icon="Star"/>
              点赞：{{ item.likes }}
            </span>
          </div>
        </div>
        <div class="v-article-operation">
          <v-icon icon="Edit" @click="doWriteArticle(item)"/>
          <el-popconfirm title="是否删除该文章？" placement="top" @confirm="removeArticle(item)">
            <template #reference>
              <v-icon icon="DeleteFilled" color="#F56C6C"/>
            </template>
          </el-popconfirm>
          <v-icon icon="View" color="#909399"/>
        </div>
      </div>
      <el-pagination v-if="totalArticleCount > 0" size="small" background
                     layout="prev, pager, next, sizes"
                     :total="totalArticleCount"
                     :page-sizes="[5, 10, 20, 50, 100]"
                     v-model:current-page="pagination.pageNum"
                     v-model:page-size="pagination.pageSize"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     class="v-article-page"/>
      <!--  暂无文章 -->
      <el-empty v-else :image-size="200" description="快去创作文章吧"/>
    </div>
  </div>
</template>

<style scoped>
.v-image-slot {
  width: 180px;
  height: 120px;
  background-color: #F5F7FA;
  display: flex;
  justify-content: center;
  align-items: center;
}

.v-article-container {
  margin: 0 auto;
  max-width: 1200px;
  
  .v-article-query {
    background-color: #ffffff;
    //border: 1px solid #cccccc;
    padding: 10px;
    margin-bottom: 10px;
    
    > h4 {
      margin-bottom: 10px;
    }
    
    > h4:before {
      content: '';
      display: inline-block;
      width: 5px;
      height: 20px;
      background-color: #646cff;
      margin-right: 5px;
      vertical-align: middle;
    }
  }
  
  .v-article-toolbar {
    background-color: #ffffff;
    padding: 4px 10px;
    box-sizing: border-box;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .v-article-total {
      font-size: 14px;
      color: #999999;
    }
  }
  
  .v-article-list {
    background-color: #ffffff;
    padding: 0 0 10px 0;
    
    .v-article-page {
      width: 100%;
      display: flex;
      justify-content: center;
    }
    
    .v-draft-status {
      //background: linear-gradient(to bottom, #faf3eb, #fffcfb);
      background: linear-gradient(to bottom, #E9E9EB, #fffcfb);
    }
    
    .v-published-status {
      background: linear-gradient(to bottom, #f3faee, #f8fcf7);
    }
    
    .v-deleted-status {
      background: linear-gradient(to bottom, #fff2f2, #fdf9f9);
    }
    
    .v-article-item {
      height: 120px;
      border: 1px solid #cccccc;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
      padding: 10px;
      margin-bottom: 10px;
      display: flex;
      
      .v-article-cover {
        width: 180px;
        height: 120px;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      .v-article-cover:hover {
        cursor: pointer;
        transform: scale(1.05);
        transition: all 0.5s ease;
      }
      
      .v-article-main {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-left: 10px;
        overflow: hidden;
        
        .v-article-title {
          height: 50px;
          width: 100%;
          font-size: 18px;
          font-weight: 600;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          /* 关键属性！解决 Flex 容器中的截断问题 */
          min-width: 0;
        }
        
        .v-article-title:hover {
          cursor: pointer;
          color: #409EFF;
          text-decoration: underline;
        }
        
        .v-article-other-info {
          font-size: 12px;
          color: #999999;
          display: flex;
          flex-direction: row;
          
          > span {
            margin-right: 10px;
            display: flex;
            align-items: center;
          }
        }
        
        > span {
          width: 100%;
          height: 100%;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.5);
          overflow: hidden;
        }
      }
      
      .v-article-operation {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
    }
    
    .v-article-item:hover {
      cursor: pointer;
      transform: scale(1.01);
      transition: all 0.5s ease;
    }
    
    
  }
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>